<template>
  <div>
    <a-modal
      :visible="open"
      title="资产出库"
      width="60%"
      @ok="onClose"
      @cancel="onClose"
    >
      <div class="position-wrap">
        <div class="floor-table">
          <div class="button-wrap">
            <a-space>
              <a-button type="primary" @click="openAddFloor = true">新增</a-button>
            </a-space>
          </div>
          <div class="table-wrap">
            <a-table :loading="floorLoading" size="middle" :dataSource="floorSource"
                     :columns="floorColumns"
                     :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'radio' }"
                     rowKey="id"
                     :customRow="customRow">
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'operation'">
                  <a-button class="button-interval" type="link" size="small"
                            @click="handleDeleteFloor(record)">删除
                  </a-button>
                </template>
              </template>
            </a-table>
          </div>
        </div>
        <div class="position-table">
          <div class="button-wrap">
            <a-space>
              <a-button type="primary" @click="showAddPosition">新增</a-button>
            </a-space>
          </div>
          <div class="table-wrap">
            <a-table :loading="positionLoading" size="middle" :dataSource="positionSource"
                     :columns="positionColumns">
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'operation'">
                  <a-button class="button-interval" type="link" size="small"
                            @click="handleDeletePosition(record)">删除
                  </a-button>
                </template>
              </template>
            </a-table>
          </div>
        </div>
      </div>
    </a-modal>
    <a-modal v-model:open="openAddFloor" title="新增楼层" @ok="handleAddFloor">
      <div style="display: flex;align-items:center;margin-top:8px">楼层：
        <a-input style="flex:1" v-model:value="newFloor"></a-input>
      </div>
    </a-modal>
    <a-modal v-model:open="openAddPosition" title="新增库房" @ok="handleAddPosition">
      <div style="display: flex;align-items:center;margin-top:8px">库房：
        <a-input style="flex:1" v-model:value="newPosition"></a-input>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import {
  ref,
  unref,
  computed,
  onMounted,
  reactive,
  watch,
  nextTick,
  defineProps,
  defineEmits
} from 'vue';
import type {FormInstance} from 'ant-design-vue';
import {message} from 'ant-design-vue';
import type {AddUserBo, AssetPageVo, FloorVo, PositionVo} from '#/api/common';
import {
  pageUserApi,
  addUserApi,
  delUserApi,
  listFloorApi,
  listPositionApi,
  addFloorApi,
  addPositionApi,
  deleteFloorApi,
  deletePositionApi
} from '#/api';

import {useAccessStore} from '@vben/stores';

const props = defineProps({
  open: {
    type: Boolean,
    required: true,
    default: false,
  },
  clientId: {
    type: String,
    required: false,
  }
});
const emit = defineEmits(['close'])
const accessStore = useAccessStore();

const floorLoading = ref(false);
const positionLoading = ref(false);
const openAddFloor = ref(false);
const openAddPosition = ref(false);

const floorSource = ref<FloorVo[]>([]);
const positionSource = ref<PositionVo[]>([]);
const selectedRowKeys = ref<string[]>([])
const newFloor = ref<string>('')
const newPosition = ref<string>('')


const floorColumns = [
  {
    title: '楼层',
    dataIndex: 'floor',
    key: 'floor',
    width: 200,
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    width: 100,
    align: 'center',
  },
];

const positionColumns = [
  {
    title: '库房',
    dataIndex: 'position',
    key: 'position',
    width: 200,
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    width: 100,
    align: 'center',
  },
];

onMounted(() => {
  console.log('onMounted')
  if (props.clientId) {
    listFloor();
  }
});
const onClose = () => {
  emit('close')
}
const floorName = computed(() => {
  console.log('here computed')
  const floor = floorSource?.value.filter(s => s.id == selectedRowKeys.value?.[0])?.[0]
  console.log('computed floor', floor)
  return floor?.floor
})
const handleAdd = () => {

  open.value = true
  nextTick(() => {
    formRef.value?.resetFields()
  })
}
const handleAddSubmit = () => {
  const _this = this;
  formRef.value
    ?.validateFields()
    .then(() => {
      addUserApi(formState).then(() => {
        message.success('新增成功');
        reload();
        open.value = false;
      });
    })
    .catch((e) => {
      console.log('表单错误', e);
      message.error('表单填写错误');
    });
};

async function listFloor() {
  floorLoading.value = true;
  const res = await listFloorApi({clientId: props.clientId}).finally(() => {
    floorLoading.value = false
  });
  floorSource.value = res;
}

async function listPosition() {
  positionLoading.value = true;
  // const floor = floorSource.value.filter(s => s.id == floorId);
  // console.log('floor', floor)
  console.log('floor name', floorName.value)
  const res = await listPositionApi({
    clientId: props.clientId,
    floorName: unref(floorName.value)
  }).finally(() => {
    positionLoading.value = false
  });
  positionSource.value = res;
}

const handleDeleteFloor = async (record:FloorVo) => {
  floorLoading.value = true
  await deleteFloorApi({id: record.id}).finally(() => {
    floorLoading.value = false
  })
  message.success("删除成功")
  await listFloor()
}

const handleDeletePosition = async (record:PositionVo) => {
  positionLoading.value = true
  await deletePositionApi({id: record.id}).finally(() => {
    positionLoading.value = false
  })
  message.success("删除成功")
  await listPosition()
}
const customRow = (record, index) => {
  return {

    onclick: () => {
      console.log(111, record.id)
      selectedRowKeys.value = [record.id]
      listPosition()
    },
  }
}
const onSelectChange = (k, selectedRows) => {
  selectedRowKeys.value = k
}

const handleAddFloor = async () => {
  await addFloorApi({clientId: props.clientId, floor: newFloor.value})
  openAddFloor.value = false
  newFloor.value = undefined
  await listFloor()

}

const handleAddPosition = async () => {

  await addPositionApi({floorId: selectedRowKeys.value[0], position: newPosition.value})
  openAddPosition.value = false
  newPosition.value = undefined
  await listPosition();
}

const showAddPosition = () => {
  if (selectedRowKeys.value == undefined || selectedRowKeys.value.length == 0) {
    message.warn("请先选择楼层")
    return
  }
  openAddPosition.value = true
}
</script>
<style lang="less">
.basic-wrap {
  margin: 0 16px;
}

.button-wrap {
  margin: 16px 0;
}

.position-wrap {
  display: flex;
}

.floor-table {
  flex: 1;
  margin-right: 24px;
  //background-color: red;
}

.position-table {
  flex: 1;

  //background-color: #0a00c2;
}
</style>
